﻿Imports System.Text.RegularExpressions
Imports System.Collections.ObjectModel
Imports System.Text
Imports System.Xml


Public Class frmTrayPad
    Dim TabFile As String
    Dim HistoryFile As String
    Dim file As XDocument

    'Overrides
    Protected Overrides Sub WndProc(ByRef m As Message)
        ' Listen for operating system messages
        Select Case m.Msg
            Case WM_WINDOWPOSCHANGING
                SnapToDesktopBorder(Me, m.LParam, 0)
        End Select
        MyBase.WndProc(m)
    End Sub


    'TrayPad
    Private Sub frmTrayPad_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TabFile = savePath & "tabsV1.xml"
        HistoryFile = savePath & "history.xml"

        Dim bmp As Bitmap = My.Resources.Pad_TrayPad
        Me.Icon = Icon.FromHandle(bmp.GetHicon)

        Me.Size = My.Settings.TrayPadSize
        Me.Location = My.Settings.TrayPadLocation

        If System.IO.File.Exists(TabFile) Then
            XML_Read()

            If tabControl.TabPages.Count > 0 Then
                GetFontInformation()
                setTitleBar(tabControl.TabPages(0).Text)
                ValidateButtons(tabControl.TabPages(0).Controls(0))
            End If

            AttachFontHandlers()
        End If

        If My.Settings.npLanguage = "" Then
            tscboLanguage.SelectedIndex = 0
        Else
            tscboLanguage.SelectedIndex = tscboLanguage.Items.IndexOf(My.Settings.npLanguage)
        End If

        CheckFormOpacity()
        TrayPadHasOpened = True

        mnuFileAlwaysOnTop.Checked = My.Settings.TraypadAlwaysOnTop

        If Not System.IO.File.Exists(HistoryFile) Then
            Try
                Using sw2 As System.IO.StreamWriter = System.IO.File.CreateText(HistoryFile)
                    sw2.WriteLine("<searches />")
                    sw2.Close()
                End Using
            Catch ex As Exception
                MessageBox.Show("Could not create history.xml template file. " & ex.Message)
            End Try
        End If

        Try
            file = XDocument.Load(HistoryFile)
            LoadHistory()
        Catch ex As Exception
            MessageBox.Show("Could not load history.xml. " & ex.Message)
        End Try

    End Sub

    Private Sub frmTrayPad_Move(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Move
        My.Settings.TrayPadLocation = Me.Location
        My.Settings.Save()
    End Sub

    Private Sub frmTrayPad_ResizeEnd(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ResizeEnd
        My.Settings.TrayPadSize = Me.Size
        My.Settings.Save()
    End Sub

    Private Sub frmTrayPad_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If e.CloseReason <> CloseReason.WindowsShutDown Then
            e.Cancel = True
            Me.Hide()
        End If
    End Sub


    'SubProcedures
    Public Sub AddNewTab(ByVal origin As String)
        Dim ntp As New cTabPage

        Dim info As New XpadInfo
        info.Origin = origin
        info.FontFamily = "Calibri"
        info.FontSize = 8
        info.FontBold = True
        info.FontItalic = False

        If origin = "internal" Then
            Dim title As String = InputBox("Tab Name", "Add New Tab", "")

            Dim key As String = System.Guid.NewGuid.ToString()

            If title <> "" Then
                info.Title = title
                info.Source = savePath & key & ".txt"
                info.Monitor = False
            Else
                Exit Sub
            End If

            Try
                System.IO.File.WriteAllText(savePath & key & ".txt", "")
            Catch ex As Exception
                MessageBox.Show("Error while saving New Tab text file." & vbNewLine & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        ElseIf origin = "external" Then
            Dim tp As New frmTabProperties(info)
            If tp.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
                Exit Sub
            End If
        End If

        ntp = CreateTab(info)
        tabControl.TabPages.Add(ntp)
        tabControl.SelectedTab = ntp

        XML_Write()
    End Sub

    Private Sub DeleteTab(ByVal sender As cTabPage)
        Dim info As XpadInfo = sender.Tag

        If System.IO.File.Exists(info.Source) And info.Origin = "internal" Then
            System.IO.File.Delete(info.Source)
        End If

        tabControl.TabPages.Remove(sender)
        XML_Write()
    End Sub

    Public Sub XML_Read()
        Try
            Dim xml_doc As XDocument = XDocument.Parse(IO.File.ReadAllText(TabFile))

            Dim result = From xe In xml_doc.Descendants.Elements("tab") _
                Select New With { _
                    .title = xe.Attribute("title").Value, _
                    .source = xe.Attribute("source").Value, _
                    .origin = xe.Attribute("origin").Value, _
                    .monitor = xe.Attribute("monitor").Value, _
                    .f_family = xe.Attribute("f_family").Value, _
                    .f_size = xe.Attribute("f_size").Value, _
                    .f_bold = xe.Attribute("f_bold").Value, _
                    .f_italic = xe.Attribute("f_italic").Value _
                }

            For Each attr In result
                If System.IO.File.Exists(attr.source.ToString) Then
                    Dim info As New XpadInfo
                    info.Title = attr.title
                    info.Source = attr.source
                    info.Origin = attr.origin

                    If attr.monitor.ToString = "t" Then : info.Monitor = True
                    Else : info.Monitor = False
                    End If

                    info.FontFamily = attr.f_family.ToString
                    info.FontSize = CType(attr.f_size.ToString, Integer)
                    If attr.f_bold.ToString = "t" Then : info.FontBold = True
                    Else : info.FontBold = False
                    End If

                    If attr.f_italic.ToString = "t" Then : info.FontItalic = True
                    Else : info.FontItalic = False
                    End If

                    Try
                        tabControl.TabPages.Add(CreateTab(info))
                    Catch ex As Exception
                        MessageBox.Show("Error while loading a text file for TrayPad.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End Try

                    'If info.Monitor Then
                    '    info.TextWatcher.Filter = info.Source.Substring(info.Source.LastIndexOf("\") + 1, info.Source.Length - info.Source.LastIndexOf("\") - 1)
                    '    info.TextWatcher.Path = info.Source.Substring(0, info.Source.LastIndexOf("\"))
                    '    info.TextWatcher.IncludeSubdirectories = False
                    '    info.TextWatcher.EnableRaisingEvents = True

                    '    AddHandler info.TextWatcher.Changed, AddressOf fsw_Changed
                    'End If
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

    Public Sub XML_Write()
        Try
            Dim xmlWriter As XmlTextWriter = New XmlTextWriter(TabFile, System.Text.Encoding.UTF8)
            xmlWriter.Formatting = Formatting.Indented
            xmlWriter.WriteStartElement("tabs")

            For Each tab As cTabPage In tabControl.TabPages
                Dim info As XpadInfo = tab.Tag
                Dim tb As TextBox = tab.Controls(0)
                Dim monitor, f_bold, f_italic As String

                xmlWriter.WriteStartElement("tab")

                xmlWriter.WriteStartAttribute("title")
                xmlWriter.WriteString(info.Title)
                xmlWriter.WriteEndAttribute()

                xmlWriter.WriteStartAttribute("source")
                xmlWriter.WriteString(info.Source)
                xmlWriter.WriteEndAttribute()

                xmlWriter.WriteStartAttribute("origin")
                xmlWriter.WriteString(info.Origin)
                xmlWriter.WriteEndAttribute()

                If info.Monitor Then : monitor = "t"
                Else : monitor = "f"
                End If
                xmlWriter.WriteStartAttribute("monitor")
                xmlWriter.WriteString(monitor)
                xmlWriter.WriteEndAttribute()

                xmlWriter.WriteStartAttribute("f_family")
                xmlWriter.WriteString(tb.Font.Name)
                xmlWriter.WriteEndAttribute()

                xmlWriter.WriteStartAttribute("f_size")
                xmlWriter.WriteString(tb.Font.Size)
                xmlWriter.WriteEndAttribute()

                If tb.Font.Style.ToString.Contains("Bold") Then : f_bold = "t"
                Else : f_bold = "f"
                End If
                xmlWriter.WriteStartAttribute("f_bold")
                xmlWriter.WriteString(f_bold)
                xmlWriter.WriteEndAttribute()

                If tb.Font.Style.ToString.Contains("Italic") Then : f_italic = "t"
                Else : f_italic = "f"
                End If
                xmlWriter.WriteStartAttribute("f_italic")
                xmlWriter.WriteString(f_italic)
                xmlWriter.WriteEndAttribute()

                xmlWriter.WriteEndElement()
            Next

            xmlWriter.WriteEndElement()
            xmlWriter.Close()
        Catch ex As Exception
            MessageBox.Show("Error while saving Tab information." & vbNewLine & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub FileSaveAs(ByVal sender As TextBox, ByVal strFileName As String)
        System.IO.File.WriteAllText(strFileName, sender.Text)
    End Sub

    Private Sub removeTabStop()
        For Each ctrl In Me.Controls
            ctrl.TabStop = False
        Next
    End Sub

    Private Sub returnTabStop()
        For Each ctrl In Me.Controls
            ctrl.TabStop = True
        Next
    End Sub

    Public Sub setTitleBar(ByVal tabText As String)
        With My.Settings
            If .TitleBarDisplayPad = 0 Then
                Me.Text = "TrayPad"
            ElseIf .TitleBarDisplayPad = 1 And .TitleBarRemoveTrayPad = 0 Then
                Me.Text = "TrayPad - " & tabText
            ElseIf .TitleBarRemoveTrayPad = 1 Then
                Me.Text = tabText
            End If
        End With
    End Sub

    Private Sub ModifyTabFont()
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)

        Dim f_family As New FontFamily(tscboFont.Text)
        Dim f_size As Integer = CType(tscboSize.Text, Integer)
        Dim f_style As FontStyle

        If tsbtnBold.Checked And Not tsbtnItalic.Checked Then
            f_style = FontStyle.Bold
        ElseIf Not tsbtnBold.Checked And tsbtnItalic.Checked Then
            f_style = FontStyle.Italic
        ElseIf tsbtnBold.Checked And tsbtnItalic.Checked Then
            f_style = FontStyle.Bold Or FontStyle.Italic
        End If

        Dim f As New Font(f_family, f_size, f_style)

        tb.Font = f

        XML_Write()
    End Sub

    Private Sub FontFace_Changed(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ModifyTabFont()
    End Sub

    Private Sub GetFontInformation()
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)

        Dim f As Font = tb.Font

        tscboFont.Text = f.Name
        tscboSize.Text = f.Size

        If f.Style.ToString.Contains("Bold") Then
            tsbtnBold.Checked = True
        Else
            tsbtnBold.Checked = False
        End If

        If f.Style.ToString.Contains("Italic") Then
            tsbtnItalic.Checked = True
        Else
            tsbtnItalic.Checked = False
        End If
    End Sub

    Private Sub mnuFileAlwaysOnTop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileAlwaysOnTop.Click
        mnuFileAlwaysOnTop.Checked = Not mnuFileAlwaysOnTop.Checked
        My.Settings.TraypadAlwaysOnTop = Not My.Settings.TraypadAlwaysOnTop
        My.Settings.Save()
    End Sub


    'Functions
    Public Function CreateTab(ByVal info As XpadInfo) As cTabPage
        Dim input As String = System.IO.File.ReadAllText(info.Source)

        Dim ntp As New cTabPage(info.Title)
        ntp.Tag = info
        If info.Origin = "external" Then
            ntp.ImageIndex = 0
        End If

        Dim FontStyle As FontStyle
        If info.FontBold And Not info.FontItalic Then
            FontStyle = FontStyle.Bold
        ElseIf Not info.FontBold And info.FontItalic Then
            FontStyle = FontStyle.Italic
        ElseIf info.FontBold And info.FontItalic Then
            FontStyle = FontStyle.Bold Or FontStyle.Italic
        End If

        Dim font As New Font(info.FontFamily, info.FontSize, FontStyle)

        Dim ntb As New TextBox
        ntb.Dock = DockStyle.Fill
        ntb.ContextMenuStrip = cmnuTextBox
        ntb.Multiline = True
        ntb.Text = input
        ntb.DeselectAll()
        ntb.Font = font
        ntb.ScrollBars = ScrollBars.Vertical
        ntb.AcceptsTab = True

        If info.Monitor Then
            ntb.ReadOnly = True
        ElseIf Not info.Monitor Then
            AddHandler ntb.TextChanged, AddressOf TextBox_TextChanged
        End If
        AddHandler ntb.GotFocus, AddressOf TextBox_GotFocus
        AddHandler ntb.LostFocus, AddressOf TextBox_LostFocus
        AddHandler ntb.KeyDown, AddressOf TextBox_KeyDown
        AddHandler ntb.KeyUp, AddressOf TextBox_KeyUp
        AddHandler ntb.MouseDown, AddressOf TextBox_MouseDown
        AddHandler ntb.MouseUp, AddressOf TextBox_MouseUp

        ntp.Controls.Add(ntb)

        Return ntp
    End Function

    Function ValidateButtons(ByVal sender As TextBox)
        Dim selectedText As String = sender.SelectedText

        If selectedText = "" Then
            cmnuCopy.Enabled = False
            tsbtnCopy.Enabled = False

            cmnuCut.Enabled = False
            tsbtnCut.Enabled = False

            cmnuCasing.Enabled = False
        Else
            cmnuCopy.Enabled = True
            tsbtnCopy.Enabled = True

            cmnuCut.Enabled = True
            tsbtnCut.Enabled = True

            cmnuCasing.Enabled = True
        End If

        If Clipboard.ContainsText Then
            cmnuPaste.Enabled = True
            tsbtnPaste.Enabled = True
        Else
            cmnuPaste.Enabled = False
            tsbtnPaste.Enabled = False
        End If

        If IsValid_URL_Address(selectedText) Then
            cmnuLoadURL.Enabled = True
            tsbtnLoadURL.Enabled = True
        Else
            cmnuLoadURL.Enabled = False
            tsbtnLoadURL.Enabled = False
        End If

        Return selectedText
    End Function

    Function IsValid_URL_Address(ByVal sURLAdd As String)
        Return Regex.IsMatch(sURLAdd, "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$")
    End Function

    Public Function GetCaretInfo(ByRef txt As TextBox) As String
        Return String.Format("Line {0} Col {1}", (txt.GetLineFromCharIndex(txt.SelectionStart) + 1), (txt.SelectionStart - txt.GetFirstCharIndexOfCurrentLine + 1))
    End Function



    'Menus
    Private Sub mnuFileSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileSaveAs.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        SaveAsDialog.FileName = tb.Name & ".txt"

        If SaveAsDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim strFileName As String = SaveAsDialog.FileName
            FileSaveAs(tb, strFileName)
        End If
    End Sub

    Private Sub mnuFilePrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFilePrint.Click
        If pDiagText.ShowDialog() = DialogResult.OK Then
            pdocText.Print()
        End If
    End Sub

    Private Sub Copy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuCopy.Click, tsbtnCopy.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        tb.Copy()
    End Sub

    Private Sub Cut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuCut.Click, tsbtnCut.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        tb.Cut()
    End Sub

    Private Sub Paste_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuPaste.Click, tsbtnPaste.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        tb.Paste()
    End Sub

    Private Sub SelectAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuSelectAll.Click, tsbtnSelectAll.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        tb.SelectAll()
    End Sub

    Private Sub mnuEditSetPrintFont_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuEditSetPrintFont.Click
        If fdPrinterFont.ShowDialog() = Windows.Forms.DialogResult.OK Then
            My.Settings.PrinterFont = fdPrinterFont.Font
            My.Settings.Save()
        End If
    End Sub

    Private Sub mnuHelpContents_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Process.Start("C:\Program Files\Syspad\syspad_help.chm")
    End Sub

    Private Sub mnuLoadURL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuLoadURL.Click
        Dim selectedText As String = ValidateButtons(tabControl.SelectedTab.Controls(0))

        If IsValid_URL_Address(selectedText) Then
            Process.Start(selectedText)
        End If
    End Sub

    Private Sub mnutxtRename_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mnutxtRename.KeyDown
        If e.KeyCode = Keys.Enter Then
            Dim tab As cTabPage = tabControl.SelectedTab
            tab.Text = mnutxtRename.Text
            CType(tab.Tag, XpadInfo).Title = mnutxtRename.Text
            cmnuTabOptions.Hide()
            XML_Write()
            setTitleBar(tabControl.SelectedTab.Text)
        End If
    End Sub

    Private Sub cmnuTabRename_Opened(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmnuTabOptions.Opened
        Dim tab As cTabPage = tabControl.SelectedTab
        mnutxtRename.Text = tab.Text
    End Sub

    Private Sub cmnuTextBox_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmnuTextBox.Opening
        ValidateButtons(tabControl.SelectedTab.Controls(0))
    End Sub

    Private Sub cmnuDeleteTab_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuDeleteTab.Click
        Dim tab As cTabPage = tabControl.SelectedTab

        If MessageBox.Show(String.Format("Are you sure you want to delete tab: '{0}'?{1}", tab.Text, IIf(CType(tab.Tag, XpadInfo).Origin = "external", String.Format("{0}This will not deleted the associated external file.", vbNewLine), "")), "Delete Tab", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
            DeleteTab(tabControl.SelectedTab)
        End If
    End Sub


    'NotePad++
    Private Sub mnuNewTab_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNewTab.Click
        mnuNewTab.Checked = True
        mnuNewWindow.Checked = False
    End Sub

    Private Sub mnuNewWindow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNewWindow.Click
        mnuNewTab.Checked = False
        mnuNewWindow.Checked = True
    End Sub

    Private Sub mnuExportToNP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExportToNP.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)

        Dim npArgs As New StringBuilder("")
        Dim tempPath As String = "C:\WINDOWS\Temp\"
        Dim exportname As String = "new"

        If mnuNewWindow.Checked = True Then
            npArgs.Append("-multiInst ")
        End If
        npArgs.Append("-ro ")
        npArgs.Append("-l" & tscboLanguage.Text & " ")
        npArgs.Append(tempPath)

        System.IO.File.WriteAllText(tempPath & exportname, tb.Text)
        npArgs.Append(exportname)

        Dim pr As New Process
        pr.StartInfo.FileName = "Notepad++.exe"
        pr.StartInfo.Arguments = npArgs.ToString
        pr.StartInfo.WorkingDirectory = tempPath
        pr.Start()
    End Sub

    Private Sub tscboLanguage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tscboLanguage.SelectedIndexChanged
        My.Settings.npLanguage = tscboLanguage.Text
        mnuLanguage.HideDropDown()
        My.Settings.Save()
    End Sub


    'Handler Manipulation
    Private Sub TextBox_TextChanged(ByVal sender As TextBox, ByVal e As System.EventArgs)
        Dim info As XpadInfo = tabControl.SelectedTab.Tag

        System.IO.File.WriteAllText(info.Source, sender.Text)
        tslCoord.Text = GetCaretInfo(sender)
    End Sub

    Private Sub TextBox_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs)
        removeTabStop()
    End Sub

    Private Sub TextBox_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs)
        returnTabStop()
    End Sub

    Private Sub TextBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        tslCoord.Text = GetCaretInfo(sender)
    End Sub

    Private Sub TextBox_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        ValidateButtons(sender)
    End Sub

    Private Sub TextBox_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        tslCoord.Text = GetCaretInfo(sender)
    End Sub

    Private Sub TextBox_MouseUp(ByVal sender As TextBox, ByVal e As System.Windows.Forms.MouseEventArgs)
        ValidateButtons(sender)
    End Sub

    Private Sub AttachFontHandlers()
        AddHandler tscboFont.SelectedIndexChanged, AddressOf ModifyTabFont
        AddHandler tscboSize.SelectedIndexChanged, AddressOf ModifyTabFont
        AddHandler tsbtnBold.Click, AddressOf ModifyTabFont
        AddHandler tsbtnItalic.Click, AddressOf ModifyTabFont
    End Sub

    Private Sub DettachFontHandlers()
        Dim modTabFont As New EventHandler(AddressOf ModifyTabFont)

        RemoveHandler tscboFont.SelectedIndexChanged, modTabFont
        RemoveHandler tscboSize.SelectedIndexChanged, modTabFont
        RemoveHandler tsbtnBold.Click, modTabFont
        RemoveHandler tsbtnItalic.Click, modTabFont
    End Sub


    'Tab Control
    Private Sub tabControl_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles tabControl.Selected
        If e.TabPage IsNot Nothing Then
            DettachFontHandlers()
            setTitleBar(e.TabPage.Text)
            GetFontInformation()
            AttachFontHandlers()
        End If
    End Sub

    Private Sub padControl_TabOrderChanged() Handles tabControl.TabOrderChanged
        DettachFontHandlers()
        GetFontInformation()
        XML_Write()
        AttachFontHandlers()
    End Sub


    'Printing
    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pdocText.PrintPage
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)

        Dim rectangleInstance As RectangleF
        rectangleInstance.Width = 785
        rectangleInstance.Height = 1025
        rectangleInstance.X = 30
        rectangleInstance.Y = 30
        Dim printFont As Font = tb.Font
        Dim charCount As Integer = 0
        Dim lineCount As Integer = 0

        Static strPrint As String = ""
        Static firstPage As Boolean = True

        If firstPage Then
            strPrint = tb.Text
            firstPage = False
        End If

        e.Graphics.MeasureString(strPrint, printFont, e.MarginBounds.Size, StringFormat.GenericTypographic, charCount, lineCount)
        e.Graphics.DrawString(strPrint, printFont, Brushes.Black, rectangleInstance)
        strPrint = strPrint.Substring(charCount)

        If strPrint.Length > 0 Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
            firstPage = True
        End If
    End Sub


    'Opacity Control
    Private Sub CheckFormOpacity()
        With My.Settings
            Me.Opacity = .TrayPadOpacity / 100
            tsmnuOpacity.Text = String.Format("Opacity: {0}%", .TrayPadOpacity)

            For Each item As ToolStripMenuItem In tsmnuOpacity.DropDownItems
                If item.Tag = .TrayPadOpacity Then
                    item.Checked = True
                Else
                    item.Checked = False
                End If
            Next
        End With

        My.Settings.Save()
    End Sub

    Private Sub mnuOpacity_Click(ByVal sender As ToolStripMenuItem, ByVal e As System.EventArgs) Handles mnuOpacity30.Click, mnuOpacity40.Click, mnuOpacity50.Click, mnuOpacity60.Click, mnuOpacity70.Click, mnuOpacity80.Click, mnuOpacity90.Click, mnuOpacity100.Click
        My.Settings.TrayPadOpacity = CType(sender.Tag, Integer)
        CheckFormOpacity()
    End Sub

    Private Sub tsbtnLoadURL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnLoadURL.Click
        Dim selectedText As String = ValidateButtons(tabControl.SelectedTab.Controls(0))

        If IsValid_URL_Address(selectedText) Then
            Process.Start(selectedText)
        End If
    End Sub

    Private Sub tsbtnAddNative_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnAddNative.Click
        DettachFontHandlers()
        AddNewTab("internal")
        AttachFontHandlers()
    End Sub

    Private Sub tsbtnAddExternal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnAddExternal.Click
        DettachFontHandlers()
        AddNewTab("external")
        AttachFontHandlers()
    End Sub

    Private Sub cmnuTabOptions_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmnuTabOptions.Opening
        Dim info As XpadInfo = tabControl.SelectedTab.Tag

        If info.Origin = "internal" Then
            cmnuProperties.Enabled = False
        ElseIf info.Origin = "external" Then
            cmnuProperties.Enabled = True
        End If
    End Sub

    Private Sub cmnuProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuProperties.Click
        Dim info As XpadInfo = tabControl.SelectedTab.Tag

        Dim tp As New frmTabProperties(info)
        If tp.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
            Exit Sub
        End If

        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)

        'If info.Monitor Then
        '    tb.ReadOnly = True

        '    info.TextWatcher.Filter = info.Source.Substring(info.Source.LastIndexOf("\") + 1, info.Source.Length - info.Source.LastIndexOf("\") - 1)
        '    info.TextWatcher.Path = info.Source.Substring(0, info.Source.LastIndexOf("\"))
        '    info.TextWatcher.EnableRaisingEvents = True
        '    info.TextWatcher.IncludeSubdirectories = False
        '    'info.TextWatcher.NotifyFilter = IO.NotifyFilters.LastAccess

        '    AddHandler info.TextWatcher.Changed, AddressOf fsw_Changed

        '    Dim changed As New EventHandler(AddressOf TextBox_TextChanged)
        '    RemoveHandler tb.TextChanged, changed

        'ElseIf Not info.Monitor Then
        '    tb.ReadOnly = False
        '    AddHandler tb.TextChanged, AddressOf TextBox_TextChanged

        '    info.TextWatcher.EnableRaisingEvents = False

        'End If

        XML_Write()
    End Sub

    'CODE FOR FILE MONITORING
    'Public Delegate Sub UpdateText(ByVal message As String(), ByRef tb As TextBox())
    'Private Sub fsw_Changed(ByVal sender As System.IO.FileSystemWatcher, ByVal e As System.IO.FileSystemEventArgs)

    '    If e.ChangeType = IO.WatcherChangeTypes.Changed Then
    '        Dim filePath As String = String.Format("{0}\{1}", sender.Path, sender.Filter)
    '        Dim input As String = String.Empty

    '        Try
    '            'sender.EnableRaisingEvents = False


    '            Dim file As System.IO.StreamReader = New System.IO.StreamReader(filePath)
    '            input = file.ReadToEnd.ToString

    '            file.Close()
    '            file.Dispose()
    '        Catch ex As Exception
    '            'MessageBox.Show(ex.Message)

    '        Finally
    '            'sender.EnableRaisingEvents = True
    '        End Try

    '        For Each ctp As cTabPage In tabControl.TabPages
    '            Dim x As XpadInfo = ctp.Tag

    '            If x.Source = filePath Then
    '                Dim tb As TextBox = ctp.Controls(0)

    '                tb.BeginInvoke(New UpdateText(AddressOf SetText), New String() {input}, New TextBox() {tb})

    '                Exit Sub
    '            End If
    '        Next

    '    End If
    'End Sub

    'Private Sub SetText(ByVal text As String(), ByRef tb As TextBox())
    '    tb(0).Text = text(0)
    'End Sub

    Private Sub cmnuTransformUpper_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuTransformUpper.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        tb.SelectedText = tb.SelectedText.ToUpper
    End Sub

    Private Sub cmnuTransformLower_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuTransformLower.Click
        Dim tb As TextBox = tabControl.SelectedTab.Controls(0)
        tb.SelectedText = tb.SelectedText.ToLower
    End Sub

    Private Sub cmnuReplace_Click(sender As System.Object, e As System.EventArgs) Handles cmnuReplace.Click
        ReplaceClick()
    End Sub

    Private Sub ReplaceClick(Optional ByVal find As String = "", Optional ByVal replace As String = "")
        Dim rt As frmReplaceText = New frmReplaceText(find, replace)

        If rt.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim tb As TextBox = tabControl.SelectedTab.Controls(0)

            If rt.Type = 0 Then
                tb.SelectedText = ReplaceText(tb.SelectedText, rt.Find, rt.Replace)
            ElseIf rt.Type = 1 Then
                tb.Text = ReplaceText(tb.Text, rt.Find, rt.Replace)
            End If

            Dim id As Integer = (From x In file.Descendants("search")
                      Select x).Count

            AddNewSearchHistory(id, rt.Find, rt.Replace)
            LoadHistory()
        End If
    End Sub

    Private Function ReplaceText(ByVal str As String, ByVal find As String, ByVal replace As String) As String
        Return str.Replace(find, replace)
    End Function

    Private Sub AddNewSearchHistory(ByVal id As Integer, ByVal find As String, ByVal replace As String)
        file.Element("searches").Add(New XElement("search", New XElement("id", id), New XElement("find", find), New XElement("replace", replace)))
        file.Save(HistoryFile)
    End Sub

    Private Sub LoadHistory()
        Dim history = (From x In file.Descendants("search")
                       Order By Convert.ToInt32(x.Element("id").Value) Descending
                       Select Find = String.Format("{0} | {1}", x.Element("find").Value, x.Element("replace").Value)).Distinct.Take(10).ToList

        If history.Count > 0 Then

            While cmnuTextReplace.DropDownItems.Count > 1
                cmnuTextReplace.DropDownItems.RemoveAt(1)
            End While

            cmnuTextReplace.DropDownItems.Add("-")

            For Each h As String In history
                Dim item As ToolStripItem = cmnuTextReplace.DropDownItems.Add(h)
                AddHandler item.Click, AddressOf cmnuSearchHistory_Click
            Next
        End If
    End Sub

    Private Sub cmnuSearchHistory_Click(sender As ToolStripItem, e As System.EventArgs)
        Dim criteria As String() = sender.Text.Split("|")

        ReplaceClick(criteria(0).Trim, criteria(1).Trim)
    End Sub
End Class